import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/moment/viewmodels/moment_detail_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/models/comment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:vista/shared/services/relation_bond.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';
import 'package:vista/shared/widgets/vacant_state.dart';

/// 生活类型动态详情页面
class MomentDetailView extends StatefulWidget {
  final String postId;

  const MomentDetailView({super.key, required this.postId});

  @override
  State<MomentDetailView> createState() => _MomentDetailViewState();
}

class _MomentDetailViewState extends State<MomentDetailView> {
  PageController? _pageController;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<MomentDetailViewModel>.reactive(
      viewModelBuilder:
          () => MomentDetailViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<PostStudio>(),
            getIt.get<RelationBond>(),
            widget.postId,
          )..initialize(),
      builder: (context, model, child) {
        if (model.isBusy || model.post == null) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: [
                // 标题栏
                _buildHeader(context, model),
                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: [
                          // 图片展示区域
                          _buildImagesSection(context, model),
                          SizedBox(height: 14.h),
                          // 发布者信息和内容文字（合并）
                          _buildAuthorAndContentSection(context, model),
                          SizedBox(height: 14.h),
                          // 评论列表
                          _buildCommentsSection(context, model),
                          SizedBox(height: 100.h), // 底部留白
                        ]
                        .verticalShot(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                        )
                        .frameHorizontal(14.w),
                  ),
                ),
                // 评论输入框
                _buildCommentInput(context, model),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context, MomentDetailViewModel model) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => getIt.get<NavigationService>().back(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 举报按钮
          GestureDetector(
            onTap: () async {
              await ComplainHelper.unveil(
                context,
                onComplain: (reason) async {
                  await model.deletePost();
                  if (context.mounted) {
                    getIt.get<NavigationService>().back();
                    FlashNotifier.flashSuccess('Report submitted successfully');
                  }
                },
              );
            },
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建图片展示区域
  Widget _buildImagesSection(
    BuildContext context,
    MomentDetailViewModel model,
  ) {
    if (model.post == null || model.post!.images.isEmpty) {
      return const SizedBox.shrink();
    }

    final images = model.post!.images;

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: ColorConstants.blackColor,
            blurRadius: 0,
            offset: Offset(4, 4),
            spreadRadius: 0,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: SizedBox(
          height: 300.h,
          child: Stack(
            children: [
              // 主图片展示区域（PageView）- 撑满整个容器
              Positioned.fill(
                child: PageView.builder(
                  controller: _pageController,
                  onPageChanged: (index) {
                    setState(() {
                      _currentPage = index;
                    });
                  },
                  itemCount: images.length,
                  itemBuilder: (context, index) {
                    return Hero(
                      tag: 'image_${model.post!.id}_$index',
                      child: Image.asset(
                        images[index],
                        fit: BoxFit.cover,
                        width: double.infinity,
                        height: double.infinity,
                      ),
                    );
                  },
                ),
              ),
              // 右上角点赞按钮（带毛玻璃效果）
              Positioned(
                top: 12.h,
                right: 12.w,
                child: GestureDetector(
                  onTap: () async {
                    if (model.currentUser == null) {
                      final result = await showDialog<bool>(
                        context: context,
                        builder: (context) => const AuthGateModal(),
                      );
                      if (result == true && context.mounted) {
                        // 导航到登录页面并等待返回
                        await Navigator.of(context).pushNamed('/login');
                        // 返回后刷新登录状态和点赞状态
                        if (context.mounted) {
                          await model.refreshAuthAndLikeStatus();
                        }
                      }
                      return;
                    }
                    await model.toggleLike();
                  },
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.r),
                    child: BackdropFilter(
                      filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                      child: Container(
                        padding: EdgeInsets.all(10.w),
                        decoration: BoxDecoration(
                          color:
                              model.isLiked
                                  ? ColorConstants.accentColor.withOpacity(0.9)
                                  : ColorConstants.primaryColor.withOpacity(
                                    0.4,
                                  ),
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(
                            color:
                                model.isLiked
                                    ? ColorConstants.accentColor
                                    : ColorConstants.primaryColor.withOpacity(
                                      0.6,
                                    ),
                            width: 1.5.w,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: (model.isLiked
                                      ? ColorConstants.accentColor
                                      : ColorConstants.primaryColor)
                                  .withOpacity(0.3),
                              blurRadius: 8,
                              spreadRadius: 1,
                            ),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              model.isLiked
                                  ? Icons.favorite
                                  : Icons.favorite_border,
                              color: Colors.white,
                              size: 20.w,
                            ),
                            if (model.likeCount > 0) ...[
                              SizedBox(width: 6.w),
                              Text(
                                '${model.likeCount}',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              // 底部毛玻璃效果容器（包含缩略图索引）
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Container(
                  padding: EdgeInsets.symmetric(
                    vertical: 12.h,
                    horizontal: 14.w,
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(12.r),
                      bottomRight: Radius.circular(12.r),
                    ),
                  ),
                  child: SizedBox(
                    height: 50.w, // 固定高度，容纳最大的缩略图
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children:
                          images.asMap().entries.map((entry) {
                            final index = entry.key;
                            final image = entry.value;
                            final isSelected = index == _currentPage;

                            return GestureDetector(
                              onTap: () {
                                _pageController?.animateToPage(
                                  index,
                                  duration: const Duration(milliseconds: 300),
                                  curve: Curves.easeInOut,
                                );
                              },
                              child: AnimatedContainer(
                                duration: const Duration(milliseconds: 300),
                                curve: Curves.easeInOut,
                                margin: EdgeInsets.symmetric(horizontal: 4.w),
                                width: isSelected ? 50.w : 40.w,
                                height: isSelected ? 40.w : 30.w,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8.r),
                                  border: Border.all(
                                    color:
                                        isSelected
                                            ? ColorConstants.accentColor
                                            : Colors.white.withOpacity(0.6),
                                    width: isSelected ? 3.w : 1.w,
                                  ),
                                  boxShadow:
                                      isSelected
                                          ? [
                                            BoxShadow(
                                              color: ColorConstants.accentColor
                                                  .withOpacity(0.5),
                                              blurRadius: 8,
                                              spreadRadius: 2,
                                            ),
                                          ]
                                          : [],
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(8.r),
                                  child: Image.asset(image, fit: BoxFit.cover),
                                ),
                              ),
                            );
                          }).toList(),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建发布者信息和内容文字区域（合并）
  Widget _buildAuthorAndContentSection(
    BuildContext context,
    MomentDetailViewModel model,
  ) {
    if (model.author == null || model.post == null) {
      return const SizedBox.shrink();
    }

    final author = model.author!;
    final isOwnPost =
        model.currentUser != null && model.currentUser!.id == author.id;

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: ColorConstants.blackColor,
            blurRadius: 0,
            offset: Offset(4, 4),
            spreadRadius: 0,
          ),
        ],
      ),
      child: [
        // 用户信息行
        Row(
          children: [
            // 用户头像
            GestureDetector(
              onTap: () async {
                // 检查是否是当前用户
                final currentUser = await getIt<AuthFocus>().getCurrentUser();
                if (currentUser != null && currentUser.id == author.id) {
                  return; // 是自己的头像，不跳转
                }
                // 跳转到他人主页
                if (context.mounted) {
                  await Navigator.of(context).pushNamed(
                    Routes.otherProfile,
                    arguments: {'userId': author.id},
                  );
                }
              },
              child: CircleAvatar(
                radius: 22.r,
                backgroundColor: ColorConstants.primaryColor,
                backgroundImage:
                    author.avatar != null ? AssetImage(author.avatar!) : null,
                child:
                    author.avatar == null
                        ? Icon(Icons.person, size: 28.w, color: Colors.white)
                        : null,
              ),
            ),
            SizedBox(width: 12.w),
            // 用户名和签名
            Expanded(
              child: [
                // 用户名
                Text(
                  author.username,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                    color: Colors.black87,
                  ),
                ),
                // 用户签名
                if (author.signature != null)
                  Text(
                    author.signature!,
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontFamily:
                          GoogleFonts.alegreyaSans(
                            fontWeight: FontWeight.w400,
                          ).fontFamily,
                      color: Colors.black54,
                    ),
                    maxLines: 1,

                    overflow: TextOverflow.ellipsis,
                  ),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
            ),
            // 关注按钮（如果不是自己的动态）
            if (!isOwnPost)
              InkWell(
                onTap: () async {
                  if (model.currentUser == null) {
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true && context.mounted) {
                      await Navigator.of(context).pushNamed('/login');
                      if (context.mounted) {
                        await model.refreshAuthAndLikeStatus();
                      }
                    }
                    return;
                  }
                  await model.toggleFollow();
                },
                borderRadius: BorderRadius.circular(20.r),
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color:
                        model.isFollowing
                            ? ColorConstants.accentColor
                            : ColorConstants.primaryColor,
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(
                      color:
                          model.isFollowing
                              ? ColorConstants.accentColor
                              : ColorConstants.primaryColor,
                      width: 1.w,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        model.isFollowing ? Icons.check : Icons.add,
                        size: 16.w,
                        color: Colors.white,
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        model.isFollowing ? 'Following' : 'Follow',
                        style: TextStyle(fontSize: 14.sp, color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
        SizedBox(height: 14.h),
        // 内容文字
        Container(
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: ColorConstants.primaryColor.withOpacity(0.2),
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Text(
            model.post!.content,
            style: TextStyle(
              fontSize: 16.sp,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
              color: Colors.black87,
              height: 1.6,
            ),
          ),
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
    );
  }

  /// 构建评论列表区域
  Widget _buildCommentsSection(
    BuildContext context,
    MomentDetailViewModel model,
  ) {
    if (model.comments.isEmpty) {
      return Container(
        padding: EdgeInsets.all(14.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.r),
          boxShadow: [
            BoxShadow(
              color: ColorConstants.blackColor,
              blurRadius: 0,
              offset: Offset(2, 2),
              spreadRadius: 0,
            ),
          ],
        ),
        child: VacantState(
          message: 'No comments yet',
          imagePath: 'assets/images/empty2.png',
        ),
      );
    }

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.r),
        boxShadow: [
          BoxShadow(
            color: ColorConstants.blackColor,
            blurRadius: 0,
            offset: Offset(2, 2),
            spreadRadius: 0,
          ),
        ],
      ),
      child: [
        Text(
          'Comments',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w700,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 12.h),
        ...model.comments.map(
          (comment) => _buildCommentItem(context, model, comment),
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem(
    BuildContext context,
    MomentDetailViewModel model,
    CommentShot comment,
  ) {
    return FutureBuilder<UserFrame?>(
      future: model.getCommentUser(comment.userId),
      builder: (context, snapshot) {
        final user = snapshot.data;

        return Container(
          margin: EdgeInsets.only(bottom: 12.h),
          decoration: BoxDecoration(
            color: ColorConstants.primaryColor,
            borderRadius: BorderRadius.circular(10.r),
            boxShadow: [
              BoxShadow(
                color: ColorConstants.blackColor.withOpacity(0.1),
                blurRadius: 0,
                offset: Offset(2, 2),
                spreadRadius: 0,
              ),
            ],
          ),
          child: Stack(
            children: [
              // 主要内容
              Padding(
                padding: EdgeInsets.all(12.w),
                child: [
                  // 用户信息行
                  Row(
                    children: [
                      // 用户头像
                      GestureDetector(
                        onTap: () async {
                          if (user == null) return;
                          // 检查是否是当前用户
                          final currentUser =
                              await getIt<AuthFocus>().getCurrentUser();
                          if (currentUser != null &&
                              currentUser.id == user.id) {
                            return; // 是自己的头像，不跳转
                          }
                          // 跳转到他人主页
                          if (context.mounted) {
                            await Navigator.of(context).pushNamed(
                              Routes.otherProfile,
                              arguments: {'userId': user.id},
                            );
                          }
                        },
                        child: CircleAvatar(
                          radius: 15.r,
                          backgroundColor: ColorConstants.primaryColor,
                          backgroundImage:
                              user?.avatar != null
                                  ? AssetImage(user!.avatar!)
                                  : null,
                          child:
                              user?.avatar == null
                                  ? Icon(
                                    Icons.person,
                                    size: 20.w,
                                    color: Colors.white,
                                  )
                                  : null,
                        ),
                      ),
                      SizedBox(width: 10.w),
                      // 用户名
                      Expanded(
                        child: Text(
                          user?.username ?? 'Unknown',
                          style: TextStyle(
                            fontSize: 15.sp,
                            fontWeight: FontWeight.w600,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w600,
                                ).fontFamily,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 10.h),
                  // 评论内容
                  Text(
                    comment.content,
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  // 时间（右下角）
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(
                        _formatTime(comment.timestamp),
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontFamily:
                              GoogleFonts.alegreyaSans(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                          color: Colors.black54,
                        ),
                      ),
                    ],
                  ),
                ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
              ),
              // 右上角举报按钮
              Positioned(
                top: 8.h,
                right: 8.w,
                child: GestureDetector(
                  onTap: () async {
                    await ComplainHelper.unveil(
                      context,
                      onComplain: (reason) async {
                        await model.deleteComment(comment.id);
                        if (context.mounted) {
                          FlashNotifier.flashSuccess(
                            'Report submitted successfully',
                          );
                        }
                      },
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.all(6.w),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.8),
                      borderRadius: BorderRadius.circular(12.r),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 4,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    child: Image.asset(
                      'assets/images/report.png',
                      width: 16.w,
                      height: 16.w,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建评论输入框
  Widget _buildCommentInput(BuildContext context, MomentDetailViewModel model) {
    final textController = TextEditingController();

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: textController,
                decoration: InputDecoration(
                  hintText: 'Add a comment...',
                  hintStyle: TextStyle(fontSize: 14.sp, color: Colors.grey),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 1.w,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 1.w,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 2.w,
                    ),
                  ),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                ),
                maxLines: null,
                textInputAction: TextInputAction.send,
                onSubmitted: (value) async {
                  if (model.currentUser == null) {
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true && context.mounted) {
                      await Navigator.of(context).pushNamed('/login');
                      // 返回后刷新登录状态
                      if (context.mounted) {
                        await model.refreshAuthAndLikeStatus();
                      }
                    }
                    return;
                  }

                  if (value.trim().isNotEmpty) {
                    await model.addComment(value);
                    FlashNotifier.flashSuccess('Comment sent successfully');
                    textController.clear();
                  }
                },
              ),
            ),
            SizedBox(width: 8.w),
            GestureDetector(
              onTap: () async {
                if (model.currentUser == null) {
                  final result = await showDialog<bool>(
                    context: context,
                    builder: (context) => const AuthGateModal(),
                  );
                  if (result == true && context.mounted) {
                    await Navigator.of(context).pushNamed('/login');
                    // 返回后刷新登录状态
                    if (context.mounted) {
                      await model.refreshAuthAndLikeStatus();
                    }
                  }
                  return;
                }

                final content = textController.text.trim();
                if (content.isNotEmpty) {
                  await model.addComment(content);
                  FlashNotifier.flashSuccess('Comment sent successfully');
                  textController.clear();
                }
              },
              child: Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: ColorConstants.accentColor,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Image.asset(
                  'assets/images/send.png',
                  width: 20.w,
                  height: 20.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }
}
